package com.sumainfor.pc.gmio.service.impl;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.gmio.dao.*;
import com.sumainfor.pc.gmio.feign.Zfeign.ZzuulFeign;
import com.sumainfor.pc.gmio.service.SeBillOutlayService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 服务秘书 业主水电燃账单
 */
@Service
public class SeBillOutlaySerivceImpl implements SeBillOutlayService {

    private ReentrantLock lock = new ReentrantLock(false);
    Logger log= LoggerFactory.getLogger(SeBillOutlaySerivceImpl.class);
    @Autowired
    private SeBillOutlayMapper seBillOutlayMapper;
    @Autowired
    private SeGasMeterMapper seGasMeterMapper;
    @Autowired
    private SeWaterMeterMapper seWaterMeterMapper;
    @Autowired
    private SeEleMeterMapper seEleMeterMapper;
    @Autowired
    private SeTenantBillMapper seTenantBillMapper;
    @Autowired
    private ZzuulFeign zzuulFeign;
    /**
     * 服务秘书查询业主水电燃账单列表
     */
    public List<Map<String,Object>> getSeBillOutlayList(Map<String,Object> params){
        List<Map<String,Object>> gmiolist=seBillOutlayMapper.getSeBillOutlayList(params);
        List<String> idList=new ArrayList<String>();//保存账单录入人编号
        for (Map<String,Object> map : gmiolist){
            if (map.get("Create")!=null){
                idList.add(map.get("Create").toString());
            }
        }
        if (idList.size()>0){
            params.put("idList",idList);
            //到网关查询账单录入人的信息
            JsonResult zuulResult=zzuulFeign.getWegNameList(params);
            if (zuulResult.get("errorCode").equals("0")) {
                List<Map<String, Object>> zuulList=(List<Map<String, Object>>)zuulResult.get("result");
                //市场部的房源列表
                for (Map<String,Object> giomap : gmiolist){
                    if (giomap.get("Create")!=null){
                        for (Map<String,Object> mktmap : zuulList) {
                            if (mktmap.get("user_id")!=null) {
                                if (MapUtils.getString(giomap, "Create").equals(MapUtils.getString(mktmap, "user_id"))) {
                                    giomap.putAll(mktmap);
                                }
                            }
                        }
                    }
                }
            }
        }
        return gmiolist;
    }
    /**
     * 服务秘书查询业主水电燃账单列表总数
     */
    public Integer getSeBillOutlayListCount(Map<String,Object> params){
        return seBillOutlayMapper.getSeBillOutlayListCount(params);
    }
    /**
     * 租后主管撤回支出账单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateSeBillDelfg(Map<String, Object> params) {
        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                if (params.get("BiOutId")==null ||  params.get("Relation")==null
                        || params.get("PubType") ==null || params.get("BidCount")==null){
                    return result.putFailed("参数不正确+");
                }
                //是否存在收入账单 0 不存在 1 存在
                if (params.get("BidCount").toString().equals("1")){
                    if (params.get("BiId")==null){
                        return result.putFailed("参数不正确");
                    }
                }
                params.put("delfg",1);//1 记录撤回 (逻辑撤回)
                params.put("by", ContextUtils.getUserId());//操作人
                params.put("term", "4");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                //撤回 水电燃抄表记录
                // PubType 1水费 2电费 3燃气费
                Integer relCount=0;//关联账单
                if (params.get("PubType").toString().equals("1")){
                    params.put("WameId",params.get("Relation"));//水表抄表记录编号
                    relCount=seWaterMeterMapper.updateSeWaterDelfg(params);
                }else if (params.get("PubType").toString().equals("2")){
                    params.put("ElemeId",params.get("Relation"));//电表抄表记录编号
                    relCount=seEleMeterMapper.updateSeEleDelfg(params);
                }else if (params.get("PubType").toString().equals("3")){
                    params.put("GasmeId",params.get("Relation"));//燃气表抄表记录编号
                    relCount=seGasMeterMapper.updateSeGasDelfg(params);
                }else{
                    return  result.putFailed("参数异常");
                }
                //撤回支出账单
                params.put("Status","3");//账单状态 1.待支付 2.支付完成  3已废弃（业主违约等）
                Integer outCount=seBillOutlayMapper.updateSeBillDelfg(params);
                //测回收入账单
                //是否存在收入账单 0 不存在 1 存在
                Integer tenCount=0;
                if (params.get("BidCount").toString().equals("1")){
                    params.put("Status","4");//账单状态 1.待支付 2.支付完成  3已废弃（业主违约等）
                    tenCount=seTenantBillMapper.updateSeTenantDelfg(params);
                }else{
                    tenCount=1;
                }
                if (outCount >=0 && relCount >=0 && tenCount>=0){
                    result.putSuccess("操作成功");
                }else{
                    result.putFailed("服务器繁忙");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }
}
